package mq.rabbitmq.direct;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import mq.rabbitmq.RabbitMqChannelFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static com.rabbitmq.client.BuiltinExchangeType.DIRECT;
import static mq.rabbitmq.Constant.DIRECT_EX_CHANGE;
import static mq.rabbitmq.Constant.DIRECT_ROUTING_KEY;

/**
 * 消费者
 *
 * @author verlet
 * @date 2019/9/11
 */
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 声明channel
        Channel channel = RabbitMqChannelFactory.createChannel();
        /**
         * 声明exChange
         * durable: 是否持久化,durable设置为true表示持久化,反之是非持久化,持久化的可以将交换器存盘,在服务器重启的时候不会丢失信息.
         * autoDelete 是否自动删除,设置为TRUE则表是自动删除,自删除的前提是至少有一个队列或者交换器与这交换器绑定,
         *          之后所有与这个交换器绑定的队列或者交换器都与此解绑,一般都设置为false
         * internal 是否内置,如果设置 为true,则表示是内置的交换器,客户端程序无法直接发送消息到这个交换器中,只能通过交换器路由到交换器的方式
         * arguments:其它一些结构化参数比如:alternate-exchange
         */
        channel.exchangeDeclare(DIRECT_EX_CHANGE, DIRECT, true, false, false, null);
        // 声明一个队列
        String queueName = "direct_test";
        channel.queueDeclare(queueName, true, false, false, null);
        // 绑定交换机与队列的关系
        channel.queueBind(queueName, DIRECT_EX_CHANGE, DIRECT_ROUTING_KEY);
        // 创建消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                System.out.println("-------------自定义消费者------------");
                System.out.println("consumerTag : " + consumerTag);
                System.out.println("envelope : " + envelope);
                System.out.println("properties : " + properties);
                System.out.println("body : " + new String(body));
            }
        };
        // 设置channel 为自定义消费者
        channel.basicConsume(queueName, true, consumer);
        Thread.sleep(1000);
        // 关闭连接
        RabbitMqChannelFactory.close(channel);
    }
}
